package com.kung.qvs.ui.main.fragment.manage;

import android.app.Application;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableField;

import com.kung.qvs.data.JtRepository;
import com.kung.qvs.entity.BaseResultBean;
import com.kung.qvs.entity.ProductBean;
import com.kung.qvs.utils.Constants;

import java.util.concurrent.TimeUnit;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.observers.DisposableObserver;
import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.binding.command.BindingAction;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.bus.event.SingleLiveEvent;
import me.goldze.mvvmhabit.http.ResponseThrowable;
import me.goldze.mvvmhabit.utils.RxUtils;
import me.goldze.mvvmhabit.utils.ToastUtils;

public class FragWorkerAddModel extends BaseViewModel<JtRepository> {
    public FragWorkerAddModel(@NonNull Application application, JtRepository model) {
        super(application, model);
    }

    public ObservableField<Boolean> mIsUpdate = new ObservableField<>(true);    //是否为新增
    public ObservableField<String> mWorkerId = new ObservableField<>("");    //用户编号
    public ObservableField<String> mWorkerName = new ObservableField<>("");    //用户名称
    public ObservableField<String> mWorkerAccount = new ObservableField<>("");    //用户账号

    //封装一个界面发生改变的观察者
    public UIChangeObservable uc = new UIChangeObservable();

    public class UIChangeObservable {
        public SingleLiveEvent eventToLastPage = new SingleLiveEvent<>();
        public SingleLiveEvent eventSaveWorker = new SingleLiveEvent();
    }

    public BindingCommand onCommandBack = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            //返回
            uc.eventToLastPage.call();
        }
    });

    //保存
    public BindingCommand onCommandSave = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            uc.eventSaveWorker.call();
        }
    });


    public void funSaveWorker() {
        if (mWorkerAccount.get().isEmpty()) {
            ToastUtils.showShort("请输入工号");
            return;
        }
        if (mWorkerName.get().isEmpty()) {
            ToastUtils.showShort("请选择姓名");
            return;
        }

        if (mIsUpdate.get()) {
            model.reqUpdatePacker("", model.getEquipmentNo(), mWorkerId.get(), mWorkerAccount.get(), mWorkerName.get())
                    .compose(RxUtils.schedulersTransformer()) //线程调度
                    .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
                    .doOnSubscribe(this)//请求与ViewModel周期同步
                    .timeout(Constants.DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                    .doOnSubscribe(new Consumer<Disposable>() {
                        @Override
                        public void accept(Disposable disposable) throws Exception {
                            showDialog("正在保存数据...");
                        }
                    })
                    .subscribe(new DisposableObserver<BaseResultBean<Integer>>() {
                        @Override
                        public void onNext(BaseResultBean<Integer> response) {
                            //请求成功
                            if (response.isSuccess()) {
                                //数据插入本地，并根据id排序查询。已被无网络情况使用
                                uc.eventToLastPage.call();
                            } else {
                                //code错误时也可以定义Observable回调到View层去处理
                                ToastUtils.showShort(response.desc);
                            }
                        }

                        @Override
                        public void onError(Throwable throwable) {
                            //关闭对话框
                            dismissDialog();
                            if (throwable instanceof ResponseThrowable) {
                                ToastUtils.showShort(((ResponseThrowable) throwable).message);
                                //token失效，重新登录
//                            finish();
                                //如果无网络，使用本地缓存垃圾分类
                            }
                        }

                        @Override
                        public void onComplete() {
                            //关闭对话框
                            dismissDialog();
                        }
                    });
        } else {
            model.reqAddPacker("", model.getEquipmentNo(), mWorkerAccount.get(), mWorkerName.get())
                    .compose(RxUtils.schedulersTransformer()) //线程调度
                    .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
                    .doOnSubscribe(this)//请求与ViewModel周期同步
                    .timeout(Constants.DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                    .doOnSubscribe(new Consumer<Disposable>() {
                        @Override
                        public void accept(Disposable disposable) throws Exception {
                            showDialog("正在保存数据...");
                        }
                    })
                    .subscribe(new DisposableObserver<BaseResultBean<Integer>>() {
                        @Override
                        public void onNext(BaseResultBean<Integer> response) {
                            //请求成功
                            if (response.isSuccess()) {
                                //数据插入本地，并根据id排序查询。已被无网络情况使用
                                uc.eventToLastPage.call();
                            } else {
                                //code错误时也可以定义Observable回调到View层去处理
                                ToastUtils.showShort(response.desc);
                            }
                        }

                        @Override
                        public void onError(Throwable throwable) {
                            //关闭对话框
                            dismissDialog();
                            if (throwable instanceof ResponseThrowable) {
                                ToastUtils.showShort(((ResponseThrowable) throwable).message);
                                //token失效，重新登录
//                            finish();
                                //如果无网络，使用本地缓存垃圾分类
                            }
                        }

                        @Override
                        public void onComplete() {
                            //关闭对话框
                            dismissDialog();
                        }
                    });
        }
    }
}
